/**
 * Copyright 2009-2020 the original author or authors.
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.apache.ibatis.builder.xml;

import org.apache.ibatis.builder.BaseBuilder;
import org.apache.ibatis.builder.BuilderException;
import org.apache.ibatis.datasource.DataSourceFactory;
import org.apache.ibatis.executor.ErrorContext;
import org.apache.ibatis.executor.loader.ProxyFactory;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.io.VFS;
import org.apache.ibatis.logging.Log;
import org.apache.ibatis.mapping.DatabaseIdProvider;
import org.apache.ibatis.mapping.Environment;
import org.apache.ibatis.parsing.XNode;
import org.apache.ibatis.parsing.XPathParser;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.reflection.DefaultReflectorFactory;
import org.apache.ibatis.reflection.MetaClass;
import org.apache.ibatis.reflection.ReflectorFactory;
import org.apache.ibatis.reflection.factory.ObjectFactory;
import org.apache.ibatis.reflection.wrapper.ObjectWrapperFactory;
import org.apache.ibatis.session.*;
import org.apache.ibatis.transaction.TransactionFactory;
import org.apache.ibatis.type.JdbcType;

import javax.sql.DataSource;
import java.io.InputStream;
import java.io.Reader;
import java.util.Properties;

/**
 * @author Clinton Begin
 * @author Kazuki Shimizu
 */

/**
 *  父类:BaseBuilder
 *
 *   变量:protected final Configuration configuration;
 *       protected final TypeAliasRegistry typeAliasRegistry;
 *       protected final TypeHandlerRegistry typeHandlerRegistry;
 *
 *  作用:实例化XMLConfigBuilder对象 和父类的变量
 *     //构造器中的方法
 *     super(new Configuration());
 *     ErrorContext.instance().resource("SQL Mapper Configuration");
 *     this.configuration.setVariables(props);
 *     //用于标识 xml 是否解析过
 *     this.parsed = false;
 *     this.environment = environment;
 *     this.parser = parser;
 *
 *
 *    构建xml解析器XPathParser 设置配置文件是否解析过的标志位parsed
 *    存放environment
 *    localReflectorFactory ????
 */
public class XMLConfigBuilder extends BaseBuilder {

  /**
   * 是否解析过的标志位
   */
  private boolean parsed;
  /**
   * 专门用来在java中使用Xpath表达式来读取xml
   * xml解析的工具类
   */
  private final XPathParser parser;
  /**
   * <environments default="development"> <environments/>
   * environments标签中 default指定的数据源使用环境
   */
  private String environment;
  private final ReflectorFactory localReflectorFactory = new DefaultReflectorFactory();

  public XMLConfigBuilder(Reader reader) {
    this(reader, null, null);
  }

  public XMLConfigBuilder(Reader reader, String environment) {
    this(reader, environment, null);
  }

  public XMLConfigBuilder(Reader reader, String environment, Properties props) {
    this(new XPathParser(reader, true, props, new XMLMapperEntityResolver()), environment, props);
  }

  public XMLConfigBuilder(InputStream inputStream) {
    this(inputStream, null, null);
  }

  public XMLConfigBuilder(InputStream inputStream, String environment) {
    this(inputStream, environment, null);
  }

  public XMLConfigBuilder(InputStream inputStream, String environment, Properties props) {
    this(new XPathParser(inputStream, true, props, new XMLMapperEntityResolver()), environment, props);
  }

  /**
   * XMLConfigBuilder 实例化 xml配置创建对象XMLConfigBuilder
   * @param parser
   * @param environment  指定数据源的环境
   * @param props   配置文件中的 <Properties></Properties>标签的值
   */
  private XMLConfigBuilder(XPathParser parser, String environment, Properties props) {
    // 初始化Configuration 的别名库 并将 别名库和
    super(new Configuration());
    ErrorContext.instance().resource("SQL Mapper Configuration");
    // 配置文件属性对象 Properties
    this.configuration.setVariables(props);
    //用于标识 xml 是否解析过
    this.parsed = false;
    // environments标签中 default指定的数据源使用环境
    this.environment = environment;
    // 解析xml的工具类
    this.parser = parser;
  }

  /**
   * 通过XMLConfigBuilder中的解析器parser解析xml中的标签信息
   */
  public Configuration parse() {
    //不能二次解析  二次解析的时候就会抛异常
    if (parsed) {
      throw new BuilderException("Each XMLConfigBuilder can only be used once.");
    }
    parsed = true;
    // 1 将xml中的配置信息转换成XNode的Java对象
    // 2 分别解析xml中每个标签信息
    parseConfiguration(parser.evalNode("/configuration"));
    return configuration;
  }

  /**
   * 从root整个xml的配置信息中  解析每个标签的信息
   * @param root
   */
    private void parseConfiguration(XNode root) {
    try {
      // issue #117 read properties first
      // 获取 root.evalNode("properties") configuration节点下的该表达式的节点
      /**
       * 解析xml中的properties节点  并将properties标签的信息 保存在 XMLConfigBuilder中的解析器XPathParse和configuration中
       */
      propertiesElement(root.evalNode("properties"));

      Properties settings = settingsAsProperties(root.evalNode("settings"));

      loadCustomVfs(settings);

      loadCustomLogImpl(settings);
      // 解析typeAliases标签 作用: 给实体类起别名
      // <typeAliases>
      //    <package name =""  />
      //    <typeAlias alias ="" type ="" />
      // </typeAliases>
      // <package> 优先于 <typeAlias>   typeAlias 中的 alias 优先于 type
      typeAliasesElement(root.evalNode("typeAliases"));
      //  解析plugins标签 作用: 加载Interceptor 拦截器  将拦截器add到configuration中
      //  <plugins>
      //    <plugin interceptor="org.mybatis.example.ExamplePlugin">
      //      <property name="someProperty" value="100"/>
      //    </plugin>
      //  </plugins>
      pluginElement(root.evalNode("plugins"));
      objectFactoryElement(root.evalNode("objectFactory"));
      objectWrapperFactoryElement(root.evalNode("objectWrapperFactory"));
      reflectorFactoryElement(root.evalNode("reflectorFactory"));
      // 将<settings>标签中的解析的配置信息 保存到configuration中
      settingsElement(settings);
      // read it after objectFactory and objectWrapperFactory issue #631
      // 解析environments标签  作用: 数据源 和事务信息
      //  <environments default="development">
      //    <environment id="development">
      //      <transactionManager type="JDBC"/>
      //      <dataSource type="POOLED">
      //        <property name="driver" value="com.mysql.cj.jdbc.Driver"/>
      //        <property name="url" value="jdbc:mysql://127.0.0.1:3306/mybatis?serverTimezone=UTC"/>
      //        <property name="username" value="root"/>
      //        <property name="password" value="root"/>
      //      </dataSource>
      //    </environment>
      //  </environments>
      environmentsElement(root.evalNode("environments"));
      // databaseIdProvider标签的作用是 根据不同的数据库厂商执行不同的语句 参考文档:https://blog.csdn.net/ycxzuoxin/article/details/104843898/
      //<databaseIdProvider type="com.yczuoxin.databaseidorovider.MyDatabaseIdProvider">
      //    <property name="Oracle" value="oracle"/>
      //    <property name="MySQL" value="mysql"/>
      //</databaseIdProvider>
      databaseIdProviderElement(root.evalNode("databaseIdProvider"));
      // 保存 javaType jdbcType  和 TypeHandler 的关系
      // <typeHandlers>
      //    <package name="org.apache.ibatis.test.config.typehandler"/>
      //  </typeHandlers>
      typeHandlerElement(root.evalNode("typeHandlers"));
      /**
       * 解析mybatis文件有解析mappers节点的方法
       */
      mapperElement(root.evalNode("mappers"));
    } catch (Exception e) {
      throw new BuilderException("Error parsing SQL Mapper Configuration. Cause: " + e, e);
    }
  }

  /**
   *   <settings>
   *     <setting name="cacheEnabled" value="true "/>
   *   </settings>
   */
  private Properties settingsAsProperties(XNode context) {
    if (context == null) {
      return new Properties();
    }
    // 解析<settings> 标签下的  <setting> 标签信息
    Properties props = context.getChildrenAsProperties();
    // Check that all settings are known to the configuration class
    //  根据Configuration.class 获取Configuration类中的get,set,构造方法等信息
    MetaClass metaConfig = MetaClass.forClass(Configuration.class, localReflectorFactory);
    for (Object key : props.keySet()) {
      // 判断setting标签中的name属性 是不是Configuration存在的配置信息  是否提供set方法
      if (!metaConfig.hasSetter(String.valueOf(key))) {
        throw new BuilderException("The setting " + key + " is not known.  Make sure you spelled it correctly (case sensitive).");
      }
    }
    return props;
  }

  private void loadCustomVfs(Properties props) throws ClassNotFoundException {
    String value = props.getProperty("vfsImpl");
    if (value != null) {
      String[] clazzes = value.split(",");
      for (String clazz : clazzes) {
        if (!clazz.isEmpty()) {
          @SuppressWarnings("unchecked")
          Class<? extends VFS> vfsImpl = (Class<? extends VFS>) Resources.classForName(clazz);
          configuration.setVfsImpl(vfsImpl);
        }
      }
    }
  }

  private void loadCustomLogImpl(Properties props) {
    Class<? extends Log> logImpl = resolveClass(props.getProperty("logImpl"));
    configuration.setLogImpl(logImpl);
  }

  private void typeAliasesElement(XNode parent) {
    if (parent != null) {
      // TODO package 优先于 typeAlias
      for (XNode child : parent.getChildren()) {
        if ("package".equals(child.getName())) {
          String typeAliasPackage = child.getStringAttribute("name");
          //   <typeAliases>
          //    <typeAlias alias="Payment" type="org.apache.ibatis.test.entity.Payment"/>
          //    <package name="org.apache.ibatis.test.entity"/>
          //  </typeAliases>
          //获取到 <package> 节点 获取标签中的name属性 获取到包路径
          //遍历包下的.class文件 判断是否含有typeAlias注解  注解有限于xml默认别名配置
          configuration.getTypeAliasRegistry().registerAliases(typeAliasPackage);
        } else {
          String alias = child.getStringAttribute("alias");
          String type = child.getStringAttribute("type");
          try {
            Class<?> clazz = Resources.classForName(type);
            // TODO alias属性优先type属性
            if (alias == null) {
              typeAliasRegistry.registerAlias(clazz);
            } else {
              typeAliasRegistry.registerAlias(alias, clazz);
            }
          } catch (ClassNotFoundException e) {
            throw new BuilderException("Error registering typeAlias for '" + alias + "'. Cause: " + e, e);
          }
        }
      }
    }
  }

  /**
   * 解析<plugins></plugins>标签
   * @param parent
   * @throws Exception
   */
  private void pluginElement(XNode parent) throws Exception {
    if (parent != null) {
      for (XNode child : parent.getChildren()) {
        String interceptor = child.getStringAttribute("interceptor");
        Properties properties = child.getChildrenAsProperties();
        // resolveClass(interceptor) 根据interceptor中指定的类的全路径或者别名
        // 从typeAliasRegistry先已别名获取是否存在 没有则认为是全路径去加载获取Class对象
        Interceptor interceptorInstance = (Interceptor) resolveClass(interceptor)
                                          .getDeclaredConstructor().newInstance();
        interceptorInstance.setProperties(properties);
        // 将拦截器添加到 configuration 的interceptorChain 中
        configuration.addInterceptor(interceptorInstance);
      }
    }
  }

  private void objectFactoryElement(XNode context) throws Exception {
    if (context != null) {
      String type = context.getStringAttribute("type");
      Properties properties = context.getChildrenAsProperties();
      //获取
      ObjectFactory factory = (ObjectFactory) resolveClass(type).getDeclaredConstructor().newInstance();
      factory.setProperties(properties);
      configuration.setObjectFactory(factory);
    }
  }

  private void objectWrapperFactoryElement(XNode context) throws Exception {
    if (context != null) {
      String type = context.getStringAttribute("type");
      ObjectWrapperFactory factory = (ObjectWrapperFactory) resolveClass(type).getDeclaredConstructor().newInstance();
      configuration.setObjectWrapperFactory(factory);
    }
  }

  private void reflectorFactoryElement(XNode context) throws Exception {
    if (context != null) {
      String type = context.getStringAttribute("type");
      ReflectorFactory factory = (ReflectorFactory) resolveClass(type).getDeclaredConstructor().newInstance();
      configuration.setReflectorFactory(factory);
    }
  }

  /**
   * TODO  先解析properties标签是因为后续标签和properties有关联  按理想顺序解析
   * 解析xml中的properties节点  并将properties节点的值赋给  XPathParser(xml解析工具类)中的variables (properties中的值和其他标签有联系)
   *                          和 XMLConfigBuilder 父类中的configuration变量中的variables
   */
  private void propertiesElement(XNode context) throws Exception {
    if (context != null) {
      Properties defaults = context.getChildrenAsProperties();
      String resource = context.getStringAttribute("resource");
      String url = context.getStringAttribute("url");

      if (resource != null && url != null) {
        throw new BuilderException("The properties element cannot specify both a URL and a resource based property file reference.  Please specify one or the other.");
      }
      if (resource != null) {
        defaults.putAll(Resources.getResourceAsProperties(resource));
      } else if (url != null) {
        defaults.putAll(Resources.getUrlAsProperties(url));
      }
      Properties vars = configuration.getVariables();
      if (vars != null) {
        defaults.putAll(vars);
      }
      parser.setVariables(defaults);
      configuration.setVariables(defaults);
    }
  }

  private void settingsElement(Properties props) {
    configuration.setAutoMappingBehavior(AutoMappingBehavior.valueOf(props.getProperty("autoMappingBehavior", "PARTIAL")));
    configuration.setAutoMappingUnknownColumnBehavior(AutoMappingUnknownColumnBehavior.valueOf(props.getProperty("autoMappingUnknownColumnBehavior", "NONE")));
    configuration.setCacheEnabled(booleanValueOf(props.getProperty("cacheEnabled"), true));
    configuration.setProxyFactory((ProxyFactory) createInstance(props.getProperty("proxyFactory")));
    configuration.setLazyLoadingEnabled(booleanValueOf(props.getProperty("lazyLoadingEnabled"), false));
    configuration.setAggressiveLazyLoading(booleanValueOf(props.getProperty("aggressiveLazyLoading"), false));
    configuration.setMultipleResultSetsEnabled(booleanValueOf(props.getProperty("multipleResultSetsEnabled"), true));
    configuration.setUseColumnLabel(booleanValueOf(props.getProperty("useColumnLabel"), true));
    configuration.setUseGeneratedKeys(booleanValueOf(props.getProperty("useGeneratedKeys"), false));
    configuration.setDefaultExecutorType(ExecutorType.valueOf(props.getProperty("defaultExecutorType", "SIMPLE")));
    configuration.setDefaultStatementTimeout(integerValueOf(props.getProperty("defaultStatementTimeout"), null));
    configuration.setDefaultFetchSize(integerValueOf(props.getProperty("defaultFetchSize"), null));
    configuration.setDefaultResultSetType(resolveResultSetType(props.getProperty("defaultResultSetType")));
    configuration.setMapUnderscoreToCamelCase(booleanValueOf(props.getProperty("mapUnderscoreToCamelCase"), false));
    configuration.setSafeRowBoundsEnabled(booleanValueOf(props.getProperty("safeRowBoundsEnabled"), false));
    configuration.setLocalCacheScope(LocalCacheScope.valueOf(props.getProperty("localCacheScope", "SESSION")));
    configuration.setJdbcTypeForNull(JdbcType.valueOf(props.getProperty("jdbcTypeForNull", "OTHER")));
    configuration.setLazyLoadTriggerMethods(stringSetValueOf(props.getProperty("lazyLoadTriggerMethods"), "equals,clone,hashCode,toString"));
    configuration.setSafeResultHandlerEnabled(booleanValueOf(props.getProperty("safeResultHandlerEnabled"), true));
    configuration.setDefaultScriptingLanguage(resolveClass(props.getProperty("defaultScriptingLanguage")));
    configuration.setDefaultEnumTypeHandler(resolveClass(props.getProperty("defaultEnumTypeHandler")));
    configuration.setCallSettersOnNulls(booleanValueOf(props.getProperty("callSettersOnNulls"), false));
    configuration.setUseActualParamName(booleanValueOf(props.getProperty("useActualParamName"), true));
    configuration.setReturnInstanceForEmptyRow(booleanValueOf(props.getProperty("returnInstanceForEmptyRow"), false));
    configuration.setLogPrefix(props.getProperty("logPrefix"));
    configuration.setConfigurationFactory(resolveClass(props.getProperty("configurationFactory")));
    configuration.setShrinkWhitespacesInSql(booleanValueOf(props.getProperty("shrinkWhitespacesInSql"), false));
  }

  private void environmentsElement(XNode context) throws Exception {
    if (context != null) {
      if (environment == null) {
        environment = context.getStringAttribute("default");
      }
      for (XNode child : context.getChildren()) {
        String id = child.getStringAttribute("id");
        // 只解析 environments 中default指定的环境的数据源配置信息
        if (isSpecifiedEnvironment(id)) {
          // 获取配置中的事务工厂 从typeAliasRegistry中获取 获取不到则加载此类并创建实例
          TransactionFactory txFactory = transactionManagerElement(child.evalNode("transactionManager"));
          // 获取配置中的数据源工厂 从typeAliasRegistry中获取 获取不到则加载此类并创建实例
          DataSourceFactory dsFactory = dataSourceElement(child.evalNode("dataSource"));
          DataSource dataSource = dsFactory.getDataSource();
          Environment.Builder environmentBuilder = new Environment.Builder(id)
            .transactionFactory(txFactory)
            .dataSource(dataSource);
          configuration.setEnvironment(environmentBuilder.build());
        }
      }
    }
  }

  private void databaseIdProviderElement(XNode context) throws Exception {
    DatabaseIdProvider databaseIdProvider = null;
    if (context != null) {
      String type = context.getStringAttribute("type");
      // awful patch to keep backward compatibility
      if ("VENDOR".equals(type)) {
        type = "DB_VENDOR";
      }
      Properties properties = context.getChildrenAsProperties();
      databaseIdProvider = (DatabaseIdProvider) resolveClass(type).getDeclaredConstructor().newInstance();
      databaseIdProvider.setProperties(properties);
    }
    Environment environment = configuration.getEnvironment();
    if (environment != null && databaseIdProvider != null) {
      String databaseId = databaseIdProvider.getDatabaseId(environment.getDataSource());
      configuration.setDatabaseId(databaseId);
    }
  }

  /**
   * 解析事务管理transactionManager transactionManager
   * @param context
   * @return
   * @throws Exception
   */
  private TransactionFactory transactionManagerElement(XNode context) throws Exception {
    if (context != null) {
      String type = context.getStringAttribute("type");
      Properties props = context.getChildrenAsProperties();
      // 根据 type 从configuration中的在new的时候已经注册的内置的typeAliasRegistry中 此type 对应的事务管理器的 并创建实例
      TransactionFactory factory = (TransactionFactory) resolveClass(type).getDeclaredConstructor().newInstance();
      factory.setProperties(props);
      return factory;
    }
    throw new BuilderException("Environment declaration requires a TransactionFactory.");
  }

  private DataSourceFactory dataSourceElement(XNode context) throws Exception {
    if (context != null) {
      String type = context.getStringAttribute("type");
      Properties props = context.getChildrenAsProperties();
      DataSourceFactory factory = (DataSourceFactory) resolveClass(type).getDeclaredConstructor().newInstance();
      factory.setProperties(props);
      return factory;
    }
    throw new BuilderException("Environment declaration requires a DataSourceFactory.");
  }

  private void typeHandlerElement(XNode parent) {
    if (parent != null) {
      for (XNode child : parent.getChildren()) {
        if ("package".equals(child.getName())) {
          String typeHandlerPackage = child.getStringAttribute("name");
          typeHandlerRegistry.register(typeHandlerPackage);
        } else {
          String javaTypeName = child.getStringAttribute("javaType");
          String jdbcTypeName = child.getStringAttribute("jdbcType");
          String handlerTypeName = child.getStringAttribute("handler");
          Class<?> javaTypeClass = resolveClass(javaTypeName);
          JdbcType jdbcType = resolveJdbcType(jdbcTypeName);
          Class<?> typeHandlerClass = resolveClass(handlerTypeName);
          if (javaTypeClass != null) {
            if (jdbcType == null) {
              typeHandlerRegistry.register(javaTypeClass, typeHandlerClass);
            } else {
              typeHandlerRegistry.register(javaTypeClass, jdbcType, typeHandlerClass);
            }
          } else {
            typeHandlerRegistry.register(typeHandlerClass);
          }
        }
      }
    }
  }

  private void mapperElement(XNode parent) throws Exception {
    if (parent != null) {
      for (XNode child : parent.getChildren()) {
        if ("package".equals(child.getName())) {
          String mapperPackage = child.getStringAttribute("name");
          configuration.addMappers(mapperPackage);
        } else {
          String resource = child.getStringAttribute("resource");
          String url = child.getStringAttribute("url");
          String mapperClass = child.getStringAttribute("class");
          if (resource != null && url == null && mapperClass == null) {
            ErrorContext.instance().resource(resource);
            // 将resource路径的文件读取到inputStream
            InputStream inputStream = Resources.getResourceAsStream(resource);
            // 用inputStream构建一个含有xml解析器(XPathParser)的XMLMapperBuilder
            XMLMapperBuilder mapperParser = new XMLMapperBuilder(inputStream, configuration, resource, configuration.getSqlFragments());
            // parser.evalNode("/mapper")  解析Mapper.xml文件中的 <mapper>标签
            mapperParser.parse();
          } else if (resource == null && url != null && mapperClass == null) {
            //  <mapper url="">方式
            ErrorContext.instance().resource(url);
            InputStream inputStream = Resources.getUrlAsStream(url);
            XMLMapperBuilder mapperParser = new XMLMapperBuilder(inputStream, configuration, url, configuration.getSqlFragments());
            mapperParser.parse();
          } else if (resource == null && url == null && mapperClass != null) {
            //  <mapper class=""> 注解的方式 不需要使用xml
            Class<?> mapperInterface = Resources.classForName(mapperClass);
            configuration.addMapper(mapperInterface);
          } else {
            throw new BuilderException("A mapper element may only specify a url, resource or class, but not more than one.");
          }
        }
      }
    }
  }

  private boolean isSpecifiedEnvironment(String id) {
    if (environment == null) {
      throw new BuilderException("No environment specified.");
    } else if (id == null) {
      throw new BuilderException("Environment requires an id attribute.");
    } else if (environment.equals(id)) {
      return true;
    }
    return false;
  }

}
